<template>
  <div>
    <!-- 文本信息 -->
    <div>
      <!-- <div class="cameContent"></div> -->
      <div>
        <!-- <input type="file" accept="image/*" capture="camera"> -->
        <!-- 一维码 用作扫描一维码 -->
        <!-- <div><img style="width: 200px;height: 50px;" src="../../../public/code.png" alt=""></div> -->
        <!-- <div>
          <video class="camera" id="camera" width="100%" height="500" autoplay></video>
          <canvas id="canvas" style="display:none;"></canvas>
          <img class="canImg" style="width: 100%;height: 500px;"  alt="">
        </div> -->
      </div>
      <div>
        打印的信息:{{ results }}
        <!-- 自定义方式效果不好，还是用其他的包 -->
      </div>
      <div class="control">
        <el-button type="primary" @click="printTo">打印某块区域</el-button>
        <el-button type="primary" @click="createCodeToPDF">打印并在顶部添加二维码</el-button>
        <!-- <el-button type="primary" @click="decode">假设顶部二维码解码(后续用系统(uniapp)自带扫描框)</el-button> -->
        <el-button type="primary" @click="decodeByJz">测试扫码</el-button>
        <!-- <el-button type="primary" @click="deOnecode">测试扫描一维码</el-button>
        <el-button type="primary" @click="look">识别</el-button> -->

      </div>
      <div class="content" id="content" ref="content">
        <h2 class="h2">这是一张测试表单</h2>
        <div class="table">
          <el-table :data="data" style="width:100%;" border>
            <el-table-column prop="id" label="ID编号" />
            <el-table-column prop="good" label="货品名称" />
            <el-table-column prop="nums" label="货品数量" />
            <el-table-column prop="supply" label="供应商" />
            <el-table-column prop="address" label="供应商地址" />
            <el-table-column prop="qrcode" label="二维码">
              <template #default="scope">
                <img :src="scope.row.qrcode" class="w-15 h-15"></img>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 手画方式效果没问题主要是页面必须呈现在浏览器上 可以考虑采用div手绘 -->
      <div class="contentCopy">
        <div>
          <img style="width:100px;height:100px;" v-if="isCode" :src="codeSrc" alt="">
        </div>
        <div class="title">
          <h3>这是一个测试表单</h3>
        </div>
        <div v-for="(item, index) in dataCopy" :key="index">
          <div style="display:flex">
            <div class="div">{{ item.id }}</div>
            <div class="div">{{ item.good }}</div>
            <div class="div">{{ item.nums }}</div>
            <div class="div">{{ item.supply }}</div>
            <div class="div">{{ item.address }}</div>
            <div class="div">
              <img v-if="index > 0" :src="item.qrcode" class="w-15 h-15"></img>
              <div v-else-if="index == 0">二维码</div>
            </div>
          </div>
        </div>
      </div>



      <!-- 考虑采用vue-plugins-print去做 -->
      <hr />
      <h5 style="margin:10px 0;">配置vue-hiprint-print</h5>
      <index />
      <hr>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { http } from "@/utils/http";
import tem from './data/test.json'
/* 引入hiprint */
import { hiprint } from 'vue-plugin-hiprint'
/*  */
import { vPrint } from 'vue-print-next';
import { VuePrintNext } from 'vue-print-next';
import index from '@/components/custom/index.vue'
import Qr from 'qrcode-extended'
import Qrcode from '../able/qrcode.vue';
// import jzH5ScanCode from '../../../public/jz-h5-scanCode/js/index.js' 
import { scan } from '../../utils/scaner'
import Quagga from 'quagga'


const to = ref(null)


const data = ref([])
const dataCopy = ref([])
/* 获取数据 */
const getData = () => {
  http.request('Post', '/api/getPrintData', {}).then(res => {
    if (res.code == 200) {
      data.value = res.data.data.filter((el, index) => { return index != 0 })
      dataCopy.value = res.data.data
    }
  })
}
getData()

/* 定义测试数据 */

const datas = ref<any>({
  table: [
    {
      id: '1',
      good: 'xxx号螺丝刀'
    }
  ]
})




/* 打印 */
/* 样式出现问题得采用另一种方式 */
const content = ref(null)


const printTo = () => {
  new VuePrintNext({
    el: '.contentCopy',
    paperSize: 'A4',
    // orientation: 'landscape', //设置纸张方向为横向
    defaultScale: 0.8, //缩放
    /** 其他参数 */
  });
}


/* 生成pdf并打印 */
const isCode = ref(false)
const codeSrc = ref('')
const createCodeToPDF = () => {
  http.request('post', '/api/createCodeToPDF', {}).then(res => {
    if (res.code == 200) {
      isCode.value = true
      codeSrc.value = res.data
      /* 打印 */
      setTimeout(() => {
        printTo()
      }, 500)
    }
  })
}

/* 扫码 */
// const decode = () => {
//   var video = document.getElementById('camera') as HTMLCanvasElement;
//   window.navigator.mediaDevices.getUserMedia({
//     video: {
//       facingMode: 'environment'
//     }
//   })
//     .then(function (stream) {
//       // 获取video元素并设置其src为视频流
//       video.srcObject = stream;
//       setInterval(() => {
//         const canvas = document.getElementById('canvas') as HTMLCanvasElement;
//         const context = canvas.getContext('2d');
//         context.drawImage(video, 0, 0, canvas.width, canvas.height);
//         const imageURL = canvas.toDataURL('image/png')
//         to.value = imageURL
//       }, 50); // 每100毫秒检测一次二维码
//     })
//     .catch(function (error) {
//       console.error("Something went wrong!", error);
//     });
// }

const results = ref('')

const decodeByJz = async () => {
  scan().then(res => {
    results.value = res
  })
}

/* 识别 */
const look = (url) => {
  Quagga.decodeSingle({
          decoder: {
            readers: [
              "code_128_reader",
              "code_39_reader",
              "code_39_vin_reader",
              "code_93_reader",
              "ean_reader",
              "ean_5_reader",
              "ean_2_reader",
              "ean_8_reader",
              "codabar_reader",
              "upc_reader",
              "upc_e_reader",
              "i2of5_reader",
              "2of5_reader"
            ]
          },
          locate: true, // 启用定位
          src: url, // 使用文件的 URL
          locator: {
            patchSize: "large", // 使用中等大小的补丁  //"small" | "medium" | "large" 指定用于定位的图像补丁的大小。较小的补丁可能在某些情况下提供更高的精度，但会消耗更多的计算资源。
            // halfSample: true,    // 启用半采样
            area: {
              top: "100%",         // 定位区域从顶部开始
              right: "0%",      // 右侧50%
              left: "0%",       // 左侧50%
              bottom: "100%"     // 底部100%
            }
          }
        }, function (result) {
          console.log(result); // 查看完整的返回信息
          if (result && result.codeResult) {
            console.log("识别到的信息：", result.codeResult.code);
            alert(result.codeResult.code)
          } else {
            console.log("未识别到条形码");
            alert('未识别到条形码')
          }
        });
}

const videos = ref(null)

/* 扫描一维码 H5 */
/* 也可以拿来做拍照功能 */
const deOnecode = () => {
  /* 效果不好暂时不做 */
  /* 试一下input功能 */
  // var input = document.querySelector("input[type=file]");
  // input.addEventListener("change", function (e) {
  //   var file = e.target.files[0];
  //   var reader = new FileReader();
  //   reader.onload = function (e) {
  //     alert(e.target.result)
  //     var dataURL = e.target.result;
  //     // 在此处对 dataURL 进行操作，例如显示图片
  //   };
  //   reader.readAsDataURL(file);
  // });


  //创建input
  var cameContent = document.querySelector('.cameContent') as HTMLElement
  var input = document.createElement('input') as HTMLElement
  var canImg = document.querySelector('.canImg') as HTMLElement
  input.type = 'file'
  input.accept = 'image/*'
  input.capture = 'camera'
  input.style.display = 'none'
  cameContent.appendChild(input)
  //自动点击
  input.click()
  input.addEventListener('change',async (e) => {
    var file = e.target.files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
      // var dataURL = e.target.result;
      /* 转出来是base64,也可以选择blob 上边是base64 下边是blob类型*/
      // 在此处对 dataURL 进行操作，例如显示图片
      const arraybuffer = e.target.result
      const blob = new Blob([arraybuffer])
      const url = window.URL.createObjectURL(blob)
      canImg.src = url
      look(url)
    };
    // reader.readAsDataURL(file);
    reader.readAsArrayBuffer(file)
     
  })

}






</script>
<style lang="scss" scoped>
.contentCopy {
  width: 100%;

  .title {
    width: 100%;
    display: flex;
    justify-content: center;
    margin: 10px auto;
  }

  .div {
    width: 16.6vw !important;
    padding: 5px 5px;
    border: 1px solid #ebeef5 !important;
  }
}

.content {
  width: 100%;
  margin: 0 auto;

  .table {
    width: 100%;
  }

  .h2 {
    width: 100%;
    text-align: center;
    margin: 15px 0;
  }
}
</style>